import { ElMessage } from 'element-plus'

const baseUrl = ''

const fetch = (url, options) => {
  const reqUrl = baseUrl + url
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-undef
    useFetch(reqUrl, options).then(({ data: { value: res }, error }) => {
      if (error && error.value) {
        let { message } = error.value
        if (message === 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        reject(error)
        return
      }
      if (res.success) {
        resolve(res.data)
      } else {
        ElMessage.error(res.message || '系统异常,请联系管理员')
        reject(new Error(res.message || '系统异常,请联系管理员'))
      }
    })
  })
}

export class Http {
  static get(url, params = {}) {
    return fetch(url, { method: 'get', params })
  }

  static post(url, params = {}) {
    return fetch(url, { method: 'post', params })
  }

  static put(url, body) {
    return fetch(url, { method: 'put', body })
  }

  static delete(url, body) {
    return fetch(url, { method: 'delete', body })
  }
}
